# -*- coding: utf-8 -*-

from odoo import models, fields, api
from odoo.exceptions import ValidationError
import hashlib
import secrets


class ResUsers(models.Model):
    """扩展用户模型 - 添加若依风格的用户管理功能"""
    _inherit = 'res.users'
    
    # 用户基础信息
    nick_name = fields.Char('用户昵称')
    user_type = fields.Selection([
        ('00', '系统用户'),
        ('01', '注册用户')
    ], string='用户类型', default='00')
    
    # 部门相关
    department_id = fields.Many2one('device.department', '所属部门')
    post_ids = fields.Many2many(
        'device.user.post',
        'device_user_post_rel',
        'user_id',
        'post_id',
        string='岗位'
    )
    
    # 角色相关
    role_assignment_ids = fields.One2many(
        'device.user.role.assignment',
        'user_id',
        '角色分配'
    )
    role_ids = fields.Many2many(
        'device.user.role',
        'device_user_role_rel',
        'user_id',
        'role_id',
        string='用户角色',
        compute='_compute_role_ids',
        store=True
    )
    
    # 状态信息
    status = fields.Selection([
        ('0', '正常'),
        ('1', '停用')
    ], string='用户状态', default='0')
    
    del_flag = fields.Selection([
        ('0', '存在'),
        ('2', '删除')
    ], string='删除标志', default='0')
    
    # 登录相关
    login_ip = fields.Char('最后登录IP')
    login_date = fields.Datetime('最后登录时间')
    
    # 密码相关
    password_salt = fields.Char('密码盐值')
    
    # 创建和修改信息
    create_time = fields.Datetime('创建时间', default=fields.Datetime.now)
    update_time = fields.Datetime('更新时间', default=fields.Datetime.now)
    create_by = fields.Many2one('res.users', '创建者')
    update_by = fields.Many2one('res.users', '更新者')
    
    # 备注
    remark = fields.Text('备注')
    
    @api.depends('role_assignment_ids', 'role_assignment_ids.active', 'role_assignment_ids.role_id')
    def _compute_role_ids(self):
        for user in self:
            active_assignments = user.role_assignment_ids.filtered('active')
            user.role_ids = active_assignments.mapped('role_id')
    
    def write(self, vals):
        vals['update_time'] = fields.Datetime.now()
        if self.env.user:
            vals['update_by'] = self.env.user.id
        return super().write(vals)
    
    @api.model_create_multi
    def create(self, vals_list):
        for vals in vals_list:
            vals['create_time'] = fields.Datetime.now()
            if self.env.user:
                vals['create_by'] = self.env.user.id
            
            # 生成密码盐值
            if not vals.get('password_salt'):
                vals['password_salt'] = secrets.token_hex(16)
                
        return super().create(vals_list)
    
    def check_user_permissions(self, permission_code):
        """检查用户是否具有指定权限"""
        if self.env.user.has_group('base.group_system'):
            return True
            
        # 获取用户所有角色的权限
        permissions = self.role_ids.mapped('permission_ids')
        return permission_code in permissions.mapped('code')
    
    def get_user_menu_permissions(self):
        """获取用户菜单权限"""
        if self.env.user.has_group('base.group_system'):
            return self.env['device.menu.permission'].search([])
            
        return self.role_ids.mapped('menu_permission_ids')
    
    def get_user_data_scope(self):
        """获取用户数据权限范围"""
        if self.env.user.has_group('base.group_system'):
            return 'all'
            
        roles = self.role_ids
        if not roles:
            return 'self'
            
        # 取最高权限
        data_scopes = roles.mapped('data_scope')
        if '1' in data_scopes:  # 全部数据权限
            return 'all'
        elif '2' in data_scopes:  # 自定数据权限
            return 'custom'
        elif '3' in data_scopes:  # 部门数据权限
            return 'dept'
        elif '4' in data_scopes:  # 部门及以下数据权限
            return 'dept_and_child'
        else:  # 仅本人数据权限
            return 'self'
    
    def get_data_scope_department_ids(self):
        """获取数据权限部门IDs"""
        data_scope = self.get_user_data_scope()
        
        if data_scope == 'all':
            return self.env['device.department'].search([]).ids
        elif data_scope == 'custom':
            return self.role_ids.mapped('department_ids').ids
        elif data_scope == 'dept':
            return [self.department_id.id] if self.department_id else []
        elif data_scope == 'dept_and_child':
            if self.department_id:
                return self.department_id.get_children_departments().ids + [self.department_id.id]
            return []
        else:  # self
            return []


class UserPost(models.Model):
    """用户岗位"""
    _name = 'device.user.post'
    _description = '用户岗位'
    
    name = fields.Char('岗位名称', required=True)
    code = fields.Char('岗位编码', required=True)
    sequence = fields.Integer('排序', default=10)
    status = fields.Boolean('状态', default=True)
    remark = fields.Text('备注')
    
    _sql_constraints = [
        ('code_unique', 'unique(code)', '岗位编码必须唯一！')
    ]
